<template>
  <div style="margin-top: 50px"></div>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    style="max-width: 500px"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="配额名称" prop="goodsname">
      碳配额商品
      <!--      <el-input style="width: 300px" disabled placeholder="碳配额商品" />-->
    </el-form-item>
    <el-form-item
      label="交易账户"
      prop="account"
      :rule="[{ required: true, message: '请选择交易账户', trigger: 'blur' }]"
    >
      <el-select style="width: 300px" v-model="ruleForm.sellerAddress" placeholder="请选择账户">
        <el-option
          v-for="item in accounts"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      label="委托数量"
      prop="amount"
      :rule="[{ required: true, message: '请输入委托数额', trigger: 'blur' }]"
    >
      <el-input style="width: 300px" v-model="ruleForm.listingAmount" />
    </el-form-item>
    <el-form-item
      label="委托价格"
      prop="price"
      :rule="[{ required: true, message: '请输入委托价格', trigger: 'blur' }]"
    >
      <el-input style="width: 300px" v-model="ruleForm.listingPrice" />
    </el-form-item>
    <el-form-item label="可用配额">
      <el-text type="danger">{{ amount }}</el-text>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">挂牌</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watchEffect } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { ListingInfoControllerService } from '../../../generated'
import axios from 'axios'
import { getTransationEmission, quotaShare, transferToIntermediaries } from '@/utils/useWeb3'

const user = useUserStore()
const amount = ref(user.transationEmission)
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  sellerAddress: '',
  listingAmount: '',
  listingPrice: '',
  type: '0'
})

const wallet = reactive(JSON.parse(localStorage.getItem('wallet') as string) || {})
const accounts = ref([])

/**
 * 获取账户地址
 */
const getAccount = () => {
  // const accounts = await ethereum.request({ method: 'eth_requestAccounts' })

  accounts.value = [{ label: wallet.address, value: wallet.address }]
}
onMounted(() => {
  getAccount()
})
watchEffect(() => {
  getTransationEmission(wallet.address)
})

/**
 * 挂牌
 */
const submitForm = async () => {
  if (user.transationEmission < Number(ruleForm.value.listingAmount)) {
    ElMessage({
      message: '设置交易的碳配额过高',
      type: 'error'
    })
    return
  }
  //1.智能合约 转账到公共账号
  const res = await transferToIntermediaries(
    ruleForm.value.sellerAddress,
    ruleForm.value.listingAmount
  )
  if (res.status != 0) {
    ElMessage({
      message: '挂牌失败-区块链异常',
      type: 'error'
    })
    return
  } else {
    //2.添加到数据库
    const res2 = await ListingInfoControllerService.addListingUsingPost(ruleForm.value)
    if (res2.code === 0) {
      ElMessage({
        message: '挂牌成功',
        type: 'success'
      })
      //todo 跳转
    } else {
      // 区块链回溯
      await quotaShare(
        ruleForm.value.sellerAddress,
        ruleForm.value.sellerAddress,
        ruleForm.value.listingAmount
      )
      ElMessage({
        message: '挂牌失败-数据库异常',
        type: 'error'
      })
    }
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style lang="scss" scoped>
.demo-ruleForm {
  margin: 50px auto;
}
</style>
